package com.example.demo.demos.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class SignatureGenerator {
    public static void getSignature() {
        String password = "000000"; // 替换为实际密码

        // 获取当前时间戳（秒级）
        long udef_t = System.currentTimeMillis() / 1000;

        try {
            // 计算密码的MD5
            String passwordMd5 = md5(password);

            // 计算签名：SHA256(passwordMd5 + 时间戳)
            String signature = sha256(passwordMd5 + "" + udef_t);

            System.out.println("密码MD5: " + passwordMd5);
            System.out.println("时间戳: " + udef_t);
            System.out.println("签名: " + signature);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * 计算MD5哈希值
     */
    static String md5(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes());
        return bytesToHex(messageDigest);
    }

    /**
     * 计算SHA-256哈希值
     */
    static String sha256(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] messageDigest = md.digest(input.getBytes());
        return bytesToHex(messageDigest);
    }

    /**
     * 将字节数组转换为十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}